package yto.freemarker.java8.optional;

import org.junit.Test;
import yto.freemarker.java8.entity.Employee;

import java.util.Optional;

/**
 * @author dongxing
 * @create 2018-06-23 16:43
 **/
public class TestOptional01 {


    /**
     * optional容器类的常用方法
     * Optional.of(T t)：创建一个optional的实例
     * Optional.empty()：创建一个空的实例
     * Optional.ofNullable(T t)：若T为空则创建实例，否则用empty
     * <p>
     * isPresent判断是否包含值
     * orElse:默认值
     * orElseGet  函数式接口
     * <p>
     * map :如果有值对其处理，并返回optional
     * flatmap
     */
    @Test
    public void test1() {
        Optional<Employee> employee = Optional.of(new Employee());
        System.out.println(employee.get());
    }

    @Test
    public void test2() {
        Optional<Employee> employee = Optional.empty();
        System.out.println(employee.get());
    }

    @Test
    public void test3() {
        Optional<Employee> employee = Optional.ofNullable(new Employee());
        System.out.println(employee.get());
    }

    @Test
    public void test4() {
        Optional<Employee> employee = Optional.ofNullable(null);
        if (employee.isPresent()) {
            System.out.println(employee.get());
        }

        Employee employee1 = employee.orElse(new Employee("张三"));

        System.out.println(employee1);

    }

    @Test
    public void test5() {
        Optional<Employee> employee = Optional.ofNullable(null);
        if (employee.isPresent()) {
            System.out.println(employee.get());
        }
        System.out.println("-------------------------------");
        Optional<String> s = employee.map(Employee::getName);
        if (s.isPresent()) {
            System.out.println(s.get());
        }

        System.out.println("--------------------");

        //必须返回optional
        Optional<String> s1 = employee.flatMap((e) -> Optional.ofNullable(e.getName()));
        if (s1.isPresent()) {
            System.out.println(s1.get());
        }
        System.out.println("--------------------");


        Employee employee1 = employee.orElse(new Employee("张三"));

        System.out.println(employee1);

    }
}
